package controller;

import dao.UserDao;
import domain.User;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import util.JsonResult;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "/user")
public class UserController {
    @Resource
    private UserDao userDao;
    private JsonResult jsonResult=new JsonResult();

    /*根据id查询user*/
    @RequestMapping(value = "/show")
    @ResponseBody
    @Transactional
    public User show(@RequestBody Map<String,Object> map) {
        Integer tmp = (Integer)map.get("id");
        User user = userDao.selectById(tmp.longValue());
        return user;
    }

    /*插入用户*/
    @RequestMapping(value = "/insertUser")
    @ResponseBody
    @Transactional
    public JsonResult insertUser(@RequestBody  Map<String, User> map) {
        int flag = userDao.insert(map.get("user"));
        if (flag == 0) {
            jsonResult.setResult("false");
            return jsonResult;
        }
        else {
            jsonResult.setResult("true");
            return jsonResult;
        }
    }

    /*修改用户*/
    @RequestMapping(value = "/updateUser")
    @ResponseBody
    @Transactional
    public JsonResult updateUser(@RequestBody  Map<String, User> map) {
        int flag = userDao.update(map.get("user"));
        if (flag == 0) {
            jsonResult.setResult("false");
            return jsonResult;
        }
        else {
            jsonResult.setResult("true");
            return jsonResult;
        }
    }

    /*删除用户*/
    @RequestMapping(value = "/deleteUser")
    @ResponseBody
    @Transactional
    public JsonResult deleteUser(@RequestBody Map<String,Object> map) {
        int flag = userDao.delete((Integer) map.get("id"));
        if (flag == 0) {
            jsonResult.setResult("false");
            return jsonResult;
        }
        else {
            jsonResult.setResult("true");
            return jsonResult;
        }
    }

    /*查询所有用户*/
    @RequestMapping(value = "/showAll")
    @ResponseBody
    @Transactional
    public List<User> showAll() {
        List<User> users = new ArrayList<User>();
        users = userDao.selectAll();
        return users;
    }




}



